import type {VNode} from 'vue'
import {createVNode, render} from 'vue'
import Message from './index.vue'
import type {MsgOption} from './type'
import {StyleType} from './type'


let div: HTMLDivElement = document.createElement('div')
document.body.appendChild(div)

let timer: number | undefined = undefined

function showMsg(opt: MsgOption) {
  // 创建虚拟节点
  let msgVNode: VNode = createVNode(Message, {text: opt.text, type: opt.type})
  render(msgVNode, div)

  // 时间到则清除
  clearTimeout(timer)
  timer = setTimeout(() => {
    render(null, div)
  }, opt.timeout)
}

const message = {
  success(text: string, opt: MsgOption = {timeout: 3000}) {
    showMsg({
      text,
      ...opt,
      type: StyleType.success
    })
  },
  error(text: string, opt: MsgOption = {timeout: 3000}) {
    showMsg({
      text,
      ...opt,
      type: StyleType.error
    })
  },
  warn(text: string, opt: MsgOption = {timeout: 3000}) {
    showMsg({
      text,
      ...opt,
      type: StyleType.warn
    })
  }
}

export default message